package com.orangelife.mobile.login.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.PhoneCallUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.common.jump.CommonJumper;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.verify.biz.SmsHttpBiz;
import com.thirdsdk.jpush.JPushTagHelper;
import com.orangelife.mobile.util.CryptoDES;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 注册密码
 *
 * @author yw
 */
@Deprecated
public class RegisterActivity extends OrangeLifeBaseActivity {
    private TextView tvLoginTitle, tv_register;
    private LinearLayout llRegisterContactus;
    private EditText etPhone, etValidateCode, etNewPwd, et_invite;
    private Button btnGetCode, btnSubmit;
    private int timeSendSms = 59;
    private Timer timer;
    public static final String TAG = "RegisterActivity";
    private Dialog dialog;
    private HashMap<String, Object> hashMap;
    private static final int MSG_SET_TAGS = 0;

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_register);
        initView();
        findView();
    }

    public void hideInput(View v) {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    private void initView() {
        et_invite = (EditText) findViewById(R.id.et_invite);
        tvLoginTitle = (TextView) findViewById(R.id.tv_title_right);
        tv_register = (TextView) findViewById(R.id.tv_register);
        llRegisterContactus = (LinearLayout) findViewById(R.id.ll_register_contactus);
        etPhone = (EditText) findViewById(R.id.et_phone);
        etValidateCode = (EditText) findViewById(R.id.et_code);
        etNewPwd = (EditText) findViewById(R.id.et_new_pwd);
        btnGetCode = (Button) findViewById(R.id.btn_get_code);
        btnSubmit = (Button) findViewById(R.id.btn_submit);
    }

    private void findView() {
        int hui = 0;
        int shop = 0;
        tvLoginTitle.setOnClickListener(clickListener);
        llRegisterContactus.setOnClickListener(clickListener);
        btnGetCode.setOnClickListener(clickListener);
        btnSubmit.setOnClickListener(clickListener);
        tv_register.setOnClickListener(clickListener);
    }

    public void onBackClick(View v) {
        Intent data = getIntent();
        if ("register".equals(data.getStringExtra("register"))) {
            CommonJumper.jumpToMain(this);
        } else {
            finish();
        }
    }

    /**
     * 双击退出
     */
    private boolean isExit;
    @SuppressLint("HandlerLeak")
    Handler mHandler2 = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }

    };

    /**
     * 重载返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 双击退出的方法体
     */
    public void exit() {
        if (!isExit) {
            isExit = true;
            ToastHelper.getInstance()._toast(
                    getResources().getString(
                            R.string.again_according_to_exit_the_program));
            mHandler2.sendEmptyMessageDelayed(0, 2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            ExitApplication.getInstance().exit();
            this.finish();
        }
    }

    /**
     * 监听器——根据id判断并执行相应操作
     */
    View.OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (v.getId()) {
                case R.id.tv_title_right:
                    CommonJumper.jumpToLogin(RegisterActivity.this);
                    startActivity(intent);
                    break;
                case R.id.ll_register_contactus:
                    PhoneCallUtil.getInstances().PhoneCall(RegisterActivity.this,
                            Constant.CONTACT_PHONE);
                    break;
                case R.id.btn_get_code:
                    String phone = etPhone.getText().toString();
                    if (StringUtil.isContainBlank(phone)) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.register_phone_null));
                    } else if (phone.length() != 11) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.register_phone_error));
                    } else {
                        if (isConnected()) {
                            dialog = DialogHelper.getInstance().createLoadingDialog(
                                    RegisterActivity.this,
                                    getResources().getString(
                                            R.string.register_request_vercode));
                            dialog.show();
                            sendRequestForCode(phone);
                            countDownSendSmsAgain();
                        }
                    }
                    break;
                case R.id.btn_submit:
                    String phone1 = etPhone.getText().toString();
                    String password = etNewPwd.getText().toString();
                    String code = etValidateCode.getText().toString();
                    if (StringUtil.isContainBlank(phone1)) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.register_phone_null));
                    } else if (phone1.length() != 11) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.register_phone_error));
                    } else if (StringUtil.isContainBlank(password)) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.register_password_null));
                    } else if (StringUtil.isContainBlank(code)) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.register_request_vercode_null));
                    } else {
                        if (!isConnected()) {
                            return;
                        }
                        try {
                            phone1 = CryptoDES.encrypt(phone1, Constant.DES_KEY);
                            password = StringUtil.md5(password);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        dialog = DialogHelper.getInstance().createLoadingDialog(
                                RegisterActivity.this,
                                getResources().getString(
                                        R.string.register_user_info));
                        dialog.show();
                        sendRequestForRegister(phone1, password, code);
                    }
                    break;
                case R.id.tv_register:
                    IntentHelper.getInstances().getIntent(RegisterActivity.this, RegistrationProtocolActivity.class);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 用户注册请求
     *
     * @param phone1   电话
     * @param password 密码
     * @param code     验证码
     */
    private void sendRequestForRegister(String phone1, String password,
                                        String code) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("memberName", phone1);
        map.put("verifyCode", code);
        map.put("memberPsw", password);
        if (!et_invite.getText().toString().equals("")) {
            map.put("invitation", et_invite.getText().toString());
        }
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", map);
        rootMap.put("url", Constant.PATH_REGISTER);
        rootMap.put("wat", 1);
        new JSONRequest(JSONRequest.POST, rootMap, handler,
                HttpUtil.ACTION_JSON);
    }

    /**
     * 发送验证码请求
     *
     * @param phone 手机
     */
    private void sendRequestForCode(String phone) {
        SmsHttpBiz.getSmsCodeOld(phone, "1", handler, 0);
    }

    /**
     * 重置验证码时间
     */
    private void countDownSendSmsAgain() {
        /* 点击发送验证码后进行倒计时 */
        timeSendSms = 59;
        btnGetCode.setEnabled(false);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.obtainMessage(Constant.WHAT_COUNT_DOWN, timeSendSms--)
                        .sendToTarget();
            }
        }, 0, 1000);
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.WHAT_COUNT_DOWN:
                    if (timeSendSms >= 0) {
                        btnGetCode.setText(getResources().getString(R.string.wait)
                                + timeSendSms
                                + getResources().getString(R.string.seconds));
                    } else {
                        btnGetCode.setEnabled(true);
                        btnGetCode.setText(getResources().getString(
                                R.string.send_again));
                        timer.cancel();
                    }
                    break;
                default:
                    break;
            }
        }

    };
    /**
     * 接收处理线程返回的消息
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Constant.WHAT_ERROR_HTTP:
                    ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
                    break;
                case 0:
                    if (msg.obj != null) {
                        HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                                .jsonToMap(String.valueOf(msg.obj));
                        if (map != null) {
                            int errCode = Integer.parseInt(map.get(
                                    Constant.RESULT_KEY).toString());
                            String errInfo = String.valueOf(map
                                    .get(Constant.RESULT_MESSAGE_KEY));
                            Log.e(TAG, "" + msg.what);
                            if (errCode == Constant.RESULT_SUCCESS) {
                                ToastHelper.getInstance()
                                        .displayToastWithQuickClose(
                                                getResources().getString(
                                                        R.string.send_sms_success));
                            } else {
                                ToastHelper.getInstance()
                                        .displayToastWithQuickClose(errInfo);
                                timeSendSms = 0;
                            }
                        }
                    } else {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(R.string.send_sms_fail));
                        timeSendSms = 0;
                    }
                    break;
                case 1:
                    if (msg.obj != null) {
                        HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                                .jsonToMap(String.valueOf(msg.obj));
                        if (map != null) {
                            int errCode = Integer.parseInt(map.get(
                                    Constant.RESULT_KEY).toString());
                            String errInfo = String.valueOf(map
                                    .get(Constant.RESULT_MESSAGE_KEY));
                            Log.e(TAG, "" + msg.what);
                            if (errCode == Constant.RESULT_SUCCESS) {
                                ToastHelper.getInstance()
                                        .displayToastWithQuickClose(
                                                getResources().getString(
                                                        R.string.register_success));
                                HashMap<String, Object> map1 = (HashMap<String, Object>) map
                                        .get("entity");
                                hashMap = new HashMap<String, Object>();
                                hashMap.put("loginID", map1.get("loginID").toString());
                                hashMap.put("loginName", map1.get("loginName").toString());
                                hashMap.put("loginType", map1.get("loginType").toString());
                                hashMap.put("registerTime", map1.get("registerTime").toString());
                                JPushTagHelper.getInstance().setContext(RegisterActivity.this);
                                JPushTagHelper.getInstance().setTag();
                            } else {
                                ToastHelper.getInstance()
                                        .displayToastWithQuickClose(errInfo);
                            }

                        } else {
                            ToastHelper.getInstance().displayToastWithQuickClose(
                                    getResources()
                                            .getString(R.string.register_fail));
                        }
                    }
                    break;
            }
            if (dialog != null) {
                dialog.dismiss();
            }
        }

        ;
    };

}
